// 权限菜单
import { Module } from 'vuex';
import { RootState } from '../index'
import { asyncRoutes } from '@/router/path';
import { RouteRecordRaw } from 'vue-router';
import router from '@/router';

// 判断
function hasPermission(params: string[], needPermission: string) {
    for (let i = 0; i < params.length; i++) {
        // 对比 是否存在needPermission
        if (params[i].startsWith(needPermission)) {
            return true
        }
    }
    return false
}

export interface MenuState {
    menuList: RouteRecordRaw[]
}
// 过滤路由
function filterRouter(routes: RouteRecordRaw[], params: string[]) {
    // 定义一个新的数组
    const res: RouteRecordRaw[] = []
    // 遍历路由 判断 是否有相同的
    routes.forEach(route => {
        if (route.children) {
            route.children = filterRouter(route.children, params)
            if (route.children?.length > 0) {
                res.push(route)
            }
        } else {
            // 判断是否 存在 permission
            if (route.meta!.permission) {
                if (hasPermission(params, route.meta!.permission)) {
                    res.push(route)
                } else {
                    res.push(route)
                }
            }
        }
    })
    return res
}


export const menuState: Module<MenuState, RootState> = {
    namespaced: true,
    state: (): MenuState => ({
        menuList: []
    }),
    // 计算属性
    getters: {
        getMenuList: state => state.menuList
    },
    mutations: {
        setMenuList(state, systemMenu) {
            state.menuList = systemMenu
        }
    },
    actions: {
        generateSysmenuList({ commit, state }, perm: string[]) {
            let routers = filterRouter(asyncRoutes, perm)
            // 添加到动态路由
            routers.forEach(route => {
                // 二级menu跳成一级menu
                if (route.redirect == null && route.children?.length == 1) {
                    route.redirect = route.path + '/' + route.children[0].path
                    route.meta = route.children[0].meta
                }
                router.addRoute(route)
            })
            // 添加动态菜单
            commit('setMenuList', routers)
        }
    }
}